package com.flyxteam.supports.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.flyxteam.supports.distributed.trace.TraceIdManager;

public class TraceIdInterceptor implements HandlerInterceptor {

	private final static Logger LOGGER = LoggerFactory.getLogger(TraceIdInterceptor.class);

	private final static String TRACE_ID_PARAMETER_KEY = "t";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String traceId = setTraceId(request.getParameter(TRACE_ID_PARAMETER_KEY));
		LOGGER.info("traceId is {}, request url is {}, request parameter is {}", traceId, request.getRequestURL(),
				JSONObject.toJSONString(request.getParameterMap()));

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		TraceIdManager.getInstence().remove();
		LOGGER.info("remove trace id from threadlocal success");
	}

	private String setTraceId(String traceId) {
		if (traceId == null || "".equals(traceId)) {
			traceId = TraceIdManager.getInstence().generate();
		}
		TraceIdManager.getInstence().set(traceId);

		return traceId;
	}

}
